const Koa = require("koa");
const Router = require("koa-router");
const body = require("koa-bodyparser");
const ejs = require("koa-ejs");
const static = require("koa-static");
const path = require("path");
const config = require("./config");

const app = new Koa();
app.use(body());

ejs(app, {
  root: path.resolve(__dirname, "template"), // 模板的路径
  layout: false,
  viewExt: "ejs",
  cache: false,
  debug: false
});

const router = new Router();
// ctx 全局上下文，会绑定请求和响应等
router.get("/", ctx => {
  ctx.body = "主页";
});
app.use(router.routes());

router.use("/admin", require("./router/admin"));
app.use(static(path.resolve(__dirname, "public")));

app.context.config = config; // 把配置信息绑定到全局上下文中
app.context.db = require("./libs/database");
router.get("/data", async ctx => {
  const data = await ctx.db.query("select id,user,password from admin");
  ctx.body = data;
});

app.listen(3000);
